import { NextRequest, NextResponse } from 'next/server'
import { getUserFromRequest } from '@/lib/auth'
import fs from 'fs'
import path from 'path'
import { prisma } from '@/lib/db'

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ path: string[] }> }
) {
  try {
    const user = await getUserFromRequest(request)

    if (!user) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      )
    }

    const resolvedParams = await params
    const filePath = resolvedParams.path.join('/')
    const fullPath = path.join(process.cwd(), 'downloads', filePath)

    // 安全检查：确保文件路径在downloads目录内
    const downloadsDir = path.join(process.cwd(), 'downloads')
    const resolvedPath = path.resolve(fullPath)
    const resolvedDownloadsDir = path.resolve(downloadsDir)
    
    if (!resolvedPath.startsWith(resolvedDownloadsDir)) {
      return NextResponse.json(
        { error: '非法文件路径' },
        { status: 403 }
      )
    }

    // 检查文件是否存在
    if (!fs.existsSync(resolvedPath)) {
      return NextResponse.json(
        { error: '文件不存在' },
        { status: 404 }
      )
    }

    // 验证文件是否属于用户的视频记录
    const fileName = path.basename(resolvedPath)
    const videoId = fileName.split('_')[0]
    
    const video = await prisma.tikTokVideo.findFirst({
      where: {
        videoId: videoId,
        OR: [
          { localVideoPath: resolvedPath },
          { localAudioPath: resolvedPath },
          { localCoverPath: resolvedPath }
        ]
      }
    })

    if (!video) {
      return NextResponse.json(
        { error: '文件访问权限不足' },
        { status: 403 }
      )
    }

    // 读取文件
    const fileBuffer = fs.readFileSync(resolvedPath)
    
    // 获取文件类型
    const ext = path.extname(resolvedPath).toLowerCase()
    let contentType = 'application/octet-stream'
    
    switch (ext) {
      case '.mp4':
        contentType = 'video/mp4'
        break
      case '.mp3':
        contentType = 'audio/mpeg'
        break
      case '.jpg':
      case '.jpeg':
        contentType = 'image/jpeg'
        break
      case '.png':
        contentType = 'image/png'
        break
      case '.webp':
        contentType = 'image/webp'
        break
    }

    return new NextResponse(fileBuffer, {
      headers: {
        'Content-Type': contentType,
        'Content-Length': fileBuffer.length.toString(),
        'Cache-Control': 'public, max-age=31536000',
      },
    })

  } catch (error) {
    console.error('File serve error:', error)
    return NextResponse.json(
      { error: '文件服务错误' },
      { status: 500 }
    )
  }
}
